package com.wenhao.leetcode.medium;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 课程表 II
 * https://leetcode-cn.com/problems/course-schedule-ii/
 * @author Wenhao Tong
 * @create 2021-08-21 10:52
 */
public class LeetCode210 {
    List<List<Integer>> edges;
    int[] indeg;
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        edges = new ArrayList<>();
        indeg = new int[numCourses];
        // 先初始化
        for (int i = 0;i < numCourses;i++) {
            edges.add(new ArrayList<>());
        }
        // 构造图并维护入度数组
        for (int[] info : prerequisites) {
            edges.get(info[0]).add(info[1]);
            indeg[info[1]]++;
        }
        Queue<Integer> queue = new LinkedList<>();
        int[] result = new int[numCourses];
        for (int i = 0;i < numCourses;i++) {
            if (indeg[i] == 0) {
                queue.offer(i);
            }
        }
        int index = numCourses - 1;
        while (queue.size() != 0) {
            Integer poll = queue.poll();
            result[index--] = poll;
            for (Integer i : edges.get(poll)) {
                indeg[i]--;
                if (indeg[i] == 0) {
                    queue.offer(i);
                }
            }
        }
        return index == -1 ? result : new int[0];
    }
}
